from django.contrib import admin
from . import CommodityConfig
# Register your models here.
from .models import *
# admin.site.register(Types)
# admin.site.register(CommodityInfos)
admin.site.site_title = '母婴后台系统'
admin.site.site_header = "母婴电商后台管理系统"
admin.site.index_title = "母婴平台管理"

@admin.register(Types)
class TypesAdmin(admin.ModelAdmin):
    list_display = [x for x in list(Types._meta._forward_fields_map.keys())]
    search_fields = ['firsts', 'seconds']
    list_filter = ['firsts']


@admin.register(CommodityInfos)
class CommodityInfosAdmin(admin.ModelAdmin):
    list_display = [x for x in list(CommodityInfos._meta._forward_fields_map.keys())]

    search_fields = ['name']
    date_hierarchy = 'create'

    def formfield_for_dbfield(self, db_field, **kwargs):
        if db_field.name == 'types':
            db_field.choices = [(x['seconds'], x['seconds']) for x in Types.objects.values('seconds')]
        return super().formfield_for_dbfield(db_field, **kwargs)

    fieldsets = (
        ('商品信息', {
            'fields': ('name', 'sezes', 'types', 'price', 'discount')
        }),
        ('收藏数量', {
            'classes': ('collapse',),
            'fields': ('likes',),
        }),
    )
    # 将模型中的types字段下拉选择框改成水平的单选按钮
    # admin.VERTICAL  垂直
    # radio_fields = {'types': admin.HORIZONTAL}
    # 数据排序，设置后台数据列表页的默认排序方式，按照id字段进行升序排序
    ordering = ['id']
    sortable_by = ('price', 'discount')
    list_display = ['id', 'name', 'sezes', 'types', 'price', 'discount']
    list_filter = ['types']
    list_per_page = 100
    list_max_show_all = 200
    list_editable = ['name']
    search_fields = ['name', 'types']
    save_as = True
    actions_on_top = False
    actions_on_bottom = True

    list_display.append('colored_name')
    # def get_readonly_fields(self, request, obj = None):
    #     if request.user.is_superuser:
    #         self.readonly_fields = []
    #     else:
    #         self.readonly_fields = ['types']
    #     return self.readonly_fields

    def get_queryset(self, request):
        qs = super().get_queryset(request)
        if request.user.is_superuser:
            return qs
        else:
            return qs.filter(id__lt=2)

    def formfield_for_choice_field(self, db_field, request, **kwargs):
        if db_field.name == 'types':
            kwargs['choices'] = (('童装', '童装'), ('进口奶粉', '进口奶粉'))
        return super().formfield_for_choice_field(db_field, request, **kwargs)

    def save_model(self, request, obj, form, change):
        if change:
            user = request.user.username
            name = self.model.objects.get(pk=obj.pk).name
            types = form.cleaned_data['types']
            f = open("d://log.txt", 'a', encoding='utf-8')
            f.write(name + "商品类型：" + types + "被" + user + "修改" + '\r\n')
            f.close()
        else:
            pass
        super().save_model(request, obj, form, change)

    def get_datas(self, request, queryset):
        temp = []
        for d in queryset:
            t = [d.name, d.types, str(d.discount)]
            temp.append(t)
        f = open("d://data.txt", 'a', encoding='utf-8')
        for t in temp:
            f.write(",".join(t) + '\r\n')
        f.close()

        self.message_user(request, "数据导出成功")
    get_datas.short_description = "导出所选数据"
    actions = ['get_datas']